using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.Preferences;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using RestSharp;
using TheNorthStar.Api.Requests;
using TheNorthStar.Api.Results;
using NorthStar.Driver.Application;
using System.Timers;
using AutoMapper;
using Object = Java.Lang.Object;
using Timer = System.Timers.Timer;


namespace NorthStar.Driver
{
    [Activity(Label = "Home")]
    public class MainActivity : Activity
    {   
      
        string m_driverId;
        string m_bookingId;
        string m_address;
        int i = 1;
        private Timer _requestWorkTimer;
         
        private Booking RequestToSever()
        {
            var api = new ConnectToSever(Helper.GetServer(ApplicationContext));
            DriverMoreWorkRequest driver = new DriverMoreWorkRequest();
            driver.driverID = Int32.Parse( m_driverId );
            FakeGps gps = Helper.GetFakeGps(ApplicationContext);
            driver.Lat = gps.lat;
            driver.Lng = gps.lng;
            Object result = api.RequestWork( driver );
            Booking booking = Newtonsoft.Json.JsonConvert.DeserializeObject<Booking>(result.ToString());
            if (booking != null)
            {m_bookingId = booking.BookingId.ToString();
                //string add = api.GetCustomerAddress(booking);
                return booking;
            }
            else
            {
                return null;
            }
        }
        private string GetPickupAddress()
        {
            var api = new ConnectToSever(Helper.GetServer(ApplicationContext));
            DriverMoreWorkRequest driver = new DriverMoreWorkRequest();
            driver.driverID = Int32.Parse(m_driverId);
            FakeGps gps = Helper.GetFakeGps(ApplicationContext);
            driver.Lat = gps.lat;
            driver.Lng = gps.lng;

            Object result = api.RequestWork(driver);
            Booking booking = Newtonsoft.Json.JsonConvert.DeserializeObject<Booking>(result.ToString());
            if (booking != null)
            {
                return api.GetCustomerAddress(booking);
            }
            else
            {
                return "No!";
            }
        }
        private void SetDriverStatues(string status)
        {
            m_driverId = Intent.GetStringExtra("driverID");
            var api = new ConnectToSever(Helper.GetServer(ApplicationContext));
            DriverLogon driver = new DriverLogon();
            //Booking booking = RequestToSever();
            driver.driverID = Int32.Parse(m_driverId);
            driver.driverStatus = status;
            api.SetDriverStatus( driver );
        }
        private void AcceptBooking( )
        {
            m_driverId = Intent.GetStringExtra("driverID");
            var api = new ConnectToSever(Helper.GetServer(ApplicationContext));
            DriverLogon driver = new DriverLogon();
            Booking booking = RequestToSever();
            driver.driverID = Int32.Parse(m_driverId);
            if (booking != null)
            {
                //driver.driverStatus = status;
                api.AcceptAJob(driver, booking);
            }
        }
        private void CallForNewJob()
        {
            Timer t = new Timer(1000);
           // m_address = this.RequestToSever();
          
                t.Elapsed += new ElapsedEventHandler(CallForJobEverSec);
                //  t.AutoReset = true;
                t.Enabled = true;
                t.Start();
            
        }
        private  void CallForJobEverSec(object source, ElapsedEventArgs ee)
        {
            if (i == 1 || i == 3 || i == 5)
            {
                RunOnUiThread(delegate
                {
                    // string address = this.RequestToSever();
                    m_address = GetPickupAddress();
                    if (m_address != "No!")
                    {
                        AlertDialog ad = new AlertDialog.Builder(this).Create();
                        ad.SetTitle("You have a job to");
                        ad.SetMessage(m_address);
                        ad.SetButton("Accept", (s, e) =>
                        {
                            m_driverId = Intent.GetStringExtra("driverID");
                            var mact = new Intent(this, typeof(JobingActivity));
                            mact.PutExtra("driverID", m_driverId);
                            mact.PutExtra("bookingID", m_bookingId);
                            mact.PutExtra("address", m_address);

                            AcceptBooking();
                            i = -1;
                            StartActivity(mact);
                        });
                        ad.SetButton2("Reject", (s, e) => { CallForNewJob(); });
                        ad.Show();
                    }
                    // i = 0;
                });
            }
            i++;
        }
        protected override void OnDestroy()
        {
            base.OnDestroy();
            _requestWorkTimer.Stop();
        }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            
            SetContentView(Resource.Layout.Mainpage);
            //EditText messageBox = FindViewById<EditText>( Resource.Id.MessagesBox );
            Button button = FindViewById<Button>(Resource.Id.LogOutButton);

			m_driverId = Intent.GetStringExtra("driverID");
			var service = new Intent(this, typeof(NorthStarBackgroundService));
			service.PutExtra("driverId",m_driverId);
				
            StartService(service);

            ThreadPool.QueueUserWorkItem(state => SetDriverStatues("Available"));
           // this.SetDriverStatues( "Available" );

            _requestWorkTimer = new Timer(15000);
            _requestWorkTimer.Elapsed += (sender, e) =>
            {
                ThreadPool.QueueUserWorkItem(x => RequestWork());
            };
            _requestWorkTimer.Start();
            
			//this.RequestToSever();

            button.Click += (sender, args) =>
                                {
                                    SetDriverStatues( "Logoff" );
                                    var mact = new Intent(this, typeof(Activity1));
                                    mact.AddFlags(ActivityFlags.ClearTop);
                                    StartActivity(mact);
                                };

            Timer jobTimer = new Timer(1000);
            jobTimer.Elapsed += (sender, e) =>
            {
                

            };
            jobTimer.Start();
            //CallForNewJob();

        }
        private void CheckMessage()
        {
          /*  if (  )
            {
                //timeout so return home
                
            }
           /* else
            {
                timerCount--;
                RunOnUiThread(() => { jobTimerLabel.Text = string.Format("{0} seconds to respond", timerCount); });

            }*/
        }
        protected override void OnResume()
        {
            base.OnResume();
            _requestWorkTimer.Start();
        }
        private void RequestWork()
        {
            _requestWorkTimer.Stop();
            var api = new ConnectToSever(Helper.GetServer(ApplicationContext));
            DriverMoreWorkRequest driver = new DriverMoreWorkRequest();
            driver.driverID = Int32.Parse(m_driverId);
            FakeGps gps = Helper.GetFakeGps(ApplicationContext);
            driver.Lat = gps.lat;
            driver.Lng = gps.lng;
            Object result = api.RequestWork(driver);
            Booking booking = Newtonsoft.Json.JsonConvert.DeserializeObject<Booking>(result.ToString());
            if (booking != null)
            {
                m_bookingId = booking.BookingId.ToString();
                //string add = api.GetCustomerAddress(booking);

                RunOnUiThread(() =>
                {
                    var mact = new Intent(this, typeof(NewWorkAvailableActivity));
                    mact.PutExtra("driverID", m_driverId);
                    mact.PutExtra("bookingId", m_bookingId);
                    mact.PutExtra("fullAddress", booking.Address);
                    mact.PutExtra("jobLocation", booking.PickupSuburb);
                    mact.PutExtra("customerPhoneNumber", booking.PassengerPhoneNumber);

                  
                    StartActivity(mact);
                    /*AlertDialog ad = new AlertDialog.Builder(this).Create();
                    ad.SetTitle("You have a job to");
                    ad.SetMessage(m_address);
                    ad.SetButton("Accept", (s, e) =>
                    {
                        m_driverId = Intent.GetStringExtra("driverID");
                        var mact = new Intent(this, typeof(JobingActivity));
                        mact.PutExtra("driverID", m_driverId);
                        mact.PutExtra("bookingID", m_bookingId);
                        mact.PutExtra("address", m_address);

                        AcceptBooking();
                        i = -1;
                        StartActivity(mact);
                    });
                    ad.SetButton2("Reject", (s, e) => { CallForNewJob(); });
                    ad.Show();*/
                });


            }
			else
			{
				_requestWorkTimer.Start();
			}
          

           
        }


        public object even { get; set; }
    }
}